﻿using UnityEngine;
using UnityEditor;
using System.Collections;
using System;
using System.Xml;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using Common;

class ExportMap : EditorWindow
{
    private static ExportMap window;
    [MenuItem("Tools/Export map data")]
    public static void ExportItemsToData()
    {
        window = EditorWindow.GetWindow(typeof(ExportMap), false, "Export items", true) as ExportMap;
        window.position = new Rect((Screen.currentResolution.width - 400) / 2, (Screen.currentResolution.height - 380) / 2, 400, 380);
        window.InitTransform = GameObject.Find("scene001/collider/zero") as GameObject;
        window.tmp = GameObject.Instantiate(Resources.LoadAssetAtPath("Assets/Editor/map_tmp.prefab", typeof(GameObject))) as GameObject;
    }
    public GameObject InitTransform = null;
    public GameObject tmp = null;
    private Vector3 pos = Vector3.zero;
    private Vector3 tmpPos = Vector3.zero;
    private List<Transform> tmpList = new List<Transform>();
    private string stepDistanceStr = "1";
    private string chectHeightStr = "4";
    private const float stepDistance = 1;
    private const float chectHeight = 4;
    private float speed = 0;
    private bool lastCheck = true;
    private RaycastHit hit;
    void OnGUI()
    {
        GUILayout.Label("Export map data ", EditorStyles.boldLabel);
        stepDistanceStr = EditorGUILayout.TextField("Step:", stepDistanceStr);
        chectHeightStr = EditorGUILayout.TextField("Check height:", chectHeightStr);
        InitTransform = EditorGUILayout.ObjectField("Map zero:", InitTransform, typeof(GameObject)) as GameObject;
        if (GUILayout.Button("Check point"))
        {
            if (Physics.Raycast(InitTransform.transform.position, Vector3.down, out hit, 50, Define.TerrainLayerMask))
            {
                pos = hit.point;
            }
            tmp.transform.position = pos;
            CheckTmp(true);
            pos = hit.point;
            CheckTmp(false); 
            for (int i = 0; i < tmpList.Count; i++)
            {
                tmpList[i].transform.parent = tmp.transform;
            }
        }
        if (GUILayout.Button("Export"))
        {
            tmpList.Clear();
            tmpList.Add(tmp.transform);
            for (int i = 0; i < tmp.transform.childCount; i++)
            {
                tmpList.Add(tmp.transform.GetChild(i));
            }
            Transform tmpTransform;
            for (int i = tmpList.Count - 1; i > 0; i--)
            {
                for (int j = 1; j <= i; j++)
                {
                    if (tmpList[j].position.z < tmpList[j - 1].position.z)
                    {
                        tmpTransform = tmpList[j - 1];
                        tmpList[j - 1] = tmpList[j];
                        tmpList[j] = tmpTransform;
                    }
                }
            }
            //for (int i = 0; i < tmpList.Count; i++)
            //{
            //    Debug.Log(tmpList[i].transform.position.z);
            //}
            string fileName = "Assets/Editor/" + InitTransform.transform.parent.parent.name + ".dat";
            using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate))
            {
                for (int i = 0; i < tmpList.Count; i++)
                {
                    writeData(stream, tmpList[i].transform.position.y);
                    writeData(stream, tmpList[i].transform.position.z);
                }
                stream.Close();
            }
            System.Diagnostics.Process.Start("explorer", string.Concat("/select, ", Path.Combine(Environment.CurrentDirectory, fileName.Replace("/", "\\"))));
            Close();
        }
    }
    void OnDisable()
    {
        GameObject.DestroyImmediate(tmp);
    }
    byte[] buffer = null;
    void writeData(FileStream stream, float f)
    {
        buffer = BitConverter.GetBytes(f);
        for (int i = 0; i < buffer.Length; i++)
        {
            stream.WriteByte(buffer[i]);
        }
    }
    void CheckTmp(bool check)
    {
        if (check) speed = stepDistance;
        else speed = -stepDistance;
        lastCheck = true;
        while(lastCheck)
        {
            pos.z += speed;
            tmpPos = pos;
            tmpPos.y = pos.y + 5;
            lastCheck = Physics.Raycast(tmpPos, Vector3.down, out hit, 50, Define.TerrainLayerMask);
            if (lastCheck)
            {
                GameObject t = GameObject.Instantiate(tmp) as GameObject;
                t.transform.position = hit.point;
                tmpList.Add(t.transform);
            }
        }
    }
}
